
import java.util.StringTokenizer;
import java.util.Stack;
public class MyDC
{
    /** constant for addition symbol */
    private final char ADD = '+';
    /** constant for subtraction symbol */
    private final char SUBTRACT = '-';
    /** constant for multiplication symbol */
    private final char MULTIPLY = '*';
    /** constant for division symbol */
    private final char DIVIDE = '/';
    /** the stack */
    private Stack<Integer> stack;

    /**
     18    * Sets up this evalutor by creating a new stack.
     19    */
    public MyDC()
    {//构造方法使用时，可以直接为一个栈分配空间
        stack = new Stack<Integer>();//stack为堆栈对象
    }
    public int evaluate (String expr)
    {//后缀表达式的运算方法
        int op1, op2, result = 0;
        String token;
        StringTokenizer tokenizer = new StringTokenizer (expr);//使用StringTokenizer类分解String对象的字符序列，默认为空格符...
        //此时tokenizer为一个分析器
        while (tokenizer.hasMoreTokens()) {
            token = tokenizer.nextToken();
            if (isOperator(token))
            {
                op2 = (stack.pop()).intValue();//出栈
                op1 = (stack.pop()).intValue();//出栈
                result = evalSingleOp (token.charAt(0), op1, op2);//String对象第一个字符转换为char类型的方法为：str.charAt(0)
                stack.push (new Integer(result));//进栈
            }
            else {
                stack.push(new Integer(Integer.parseInt(token)));//进栈
            }
        }
        return result;
    }
    private boolean isOperator (String token)
    {
        return ( token.equals("+") || token.equals("-") ||
                token.equals("*") || token.equals("/") );
    }
    private int evalSingleOp (char operation, int op1, int op2)
    {
        int result = 0;
        switch (operation)
        {
            case ADD:
                result = op1 + op2;
                break;
            case SUBTRACT:
                result = op1 - op2;
                break;
            case MULTIPLY:
                result = op1 * op2;
                break;
            case DIVIDE:
                result = op1 / op2;
        }
        return result;
    }
}

